//
//  Canvas2ImagePlugin.m
//  Canvas2ImagePlugin PhoneGap/Cordova plugin
//
//  Created by Tommy-Carlos Williams on 29/03/12.
//  Copyright (c) 2012 Tommy-Carlos Williams. All rights reserved.
//	MIT Licensed
//

#import "Canvas2ImagePlugin.h"
#import <Cordova/CDV.h>
#import <Photos/Photos.h>

@implementation Canvas2ImagePlugin


//TODO:- 检查授权状态 type: 0(截屏) 1（保存base64图片）
- (void)checkAuthorizationStatus: (CDVInvokedUrlCommand *)command type: (int)type {
    //相册权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status != PHAuthorizationStatusAuthorized) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if(status == PHAuthorizationStatusAuthorized) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 用户点击 "OK"
                    [self saveBase64PhotoToAlbums:command];
                    
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    // 用户点击 不允许访问
                   NSURL *url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];

                    if ([[UIApplication sharedApplication] canOpenURL:url]){
                        if (@available(iOS 10.0, *)) {
                            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                        }else {
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    }
                    return;
                });
            }
        }];
    }else {
        // 已获得权限
        [self saveBase64PhotoToAlbums:command];
    }
}

//TODO:- 保存base64图片）
- (void)saveBase64PhotoToAlbums: (CDVInvokedUrlCommand *)command
{
    NSString *encodedImageStr = [command.arguments objectAtIndex:0];
    NSData *decodedImageData = [[NSData alloc] initWithBase64EncodedString:encodedImageStr options:0];
    UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

         [PHAssetChangeRequest creationRequestForAssetFromImage:decodedImage];

    } completionHandler:^(BOOL success, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{
            CDVPluginResult* pluginResult = nil;
            
             if (error) {
                 pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary: @{@"error" : error.description}];
                 NSString* callbackId = command.callbackId;
                 [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
             }else{
                 
                 NSDictionary *jsonObj = [ [NSDictionary alloc]
                     initWithObjectsAndKeys :
                     @"true", @"success",
                     nil
                 ];

                 pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:jsonObj];
                 NSString* callbackId = command.callbackId;
                 [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
            }
        });
    }];
}

//TODO:- 保存图片至本地相册 base64 图片
- (void)saveImageDataToLibrary: (CDVInvokedUrlCommand *)command
{
    [self checkAuthorizationStatus:command type:1];
    
}


@end
